package hcs.core.domain.common;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModel;
import lombok.Data;

import java.io.Serializable;

/**
 * 返回数据的包装类
 * message 是 message，data 是 data，请区分清楚
 * fail 代表的是 400，error 代表的是 500
 * 原则上 error 仅仅在全局异常捕获了位置异常的时候抛出 error
 * 其余可预知异常统统 fail
 *
 * @author draper_hxy
 */

@ApiModel(value = "R对象", description = "公共返回对象R")
@Data
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer code;

    private String message;

    private T data;

    public R() {

    }

    public R(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public static R ok() {
        return new R(200, "success");
    }


    public static <T> R ok(T data) {
        R r = R.ok();
        r.data = data;
        return r;
    }

    public static <T> R ok(String message, T data) {
        R r = new R(200, message);
        r.data = data;
        return r;
    }

    public static R fail(String message) {
        return new R(400, message);
    }

    public static R fail(Object object) {
        R r = new R(400, "操作失败");
        r.setData(object);
        return r;
    }

    public static R error(String message) {
        return new R(500, message);
    }

    public static void main(String[] args) {
        System.out.println(JSONObject.toJSONString(R.ok("hello")));
    }
}
